package org.afi.mushroomplayer.utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.afi.mushroomplayer.model.SongInfo;

import android.content.Context;
import android.database.Cursor;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.provider.MediaStore.Audio.AudioColumns;
import android.util.Log;

public class SongUtils {
    
    private static final String TAG = "SongUtils";
    
    private static final String[] PROJECTION = new String[] {
        MediaColumns.SIZE, MediaColumns.TITLE, AudioColumns.ALBUM, AudioColumns.ARTIST, AudioColumns.DURATION
    };

    private static final String SELECTION =  MediaColumns.DATA + "=?";
        
    public static SongInfo getSongInfoFromUrl(Context context, String url) {
        SongInfo info = new SongInfo();
        info.setUrl(url);
        Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, PROJECTION, SELECTION, new String[] { url }, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
        if (cursor.moveToFirst()) {
            info.setSize(BaseUtils.toSizeString(cursor.getLong(cursor.getColumnIndexOrThrow(MediaColumns.SIZE))));
            info.setTitle(cursor.getString(cursor.getColumnIndexOrThrow(MediaColumns.TITLE)));
            info.setAlbum(cursor.getString(cursor.getColumnIndexOrThrow(AudioColumns.ALBUM)));
            info.setArtist(cursor.getString(cursor.getColumnIndexOrThrow(AudioColumns.ARTIST)));
            info.setDuration(cursor.getInt(cursor.getColumnIndexOrThrow(AudioColumns.DURATION)));
            Log.d(TAG, "info = "+info.getTitle()+" "+info.getAlbum()+" "+info.getArtist()+" "+info.getDuration()+" "+info.getSize()+" "+info.getUrl());
            return info;
        } else {
            return null;
        }
    }
    
    public static List<SongInfo> sort(List<SongInfo> list, int type) {
        int length = list.size();
        List<SongInfo> sortedList = new ArrayList<SongInfo>();
        FileWrapper[] fileWrappers = new FileWrapper[length];
        for (int i = 0; i < length; i++) {
            fileWrappers[i] = new FileWrapper(list.get(i), type);
        }
        
        Arrays.sort(fileWrappers);
        for(int i=0;i<length;i++) {
            sortedList.add(fileWrappers[i].getSongInfo());
        }
        return sortedList;
    }
}
